
//
//  DoorSystemSettingViewController.m
//  RONGAO
//
//  Created by ZhangYeKun on 2017/2/24.
//  Copyright © 2017年 wei wang. All rights reserved.
//

#import "DoorSystemSettingViewController.h"
#import "DoorSystemDeviceInfoViewController.h"
#import "DoorSystemPwdSettingViewController.h"
#import "DoorSystemPushSettingViewController.h"
#import "DoorSystemVideoSettingViewController.h"
#import "DoorSystemSDCardViewController.h"
#import "DoorSystemUPdateViewController.h"
#import "DoorSystemWiFiViewController.h"
#import "DoorSystemAlarmAccessViewController.h"
@interface DoorSystemSettingViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    
    NSInteger pushNotification;
    NSInteger videoQuality;
    NSInteger recordingMode;
}
/** tableView **/
@property(nonatomic,strong) UITableView *tableView;
/** 配置文件 **/
@property(nonatomic,strong) NSArray *settingPlist;


/** <#Description#> **/
@property(nonatomic,strong) MyCamera *camera;
@end

@implementation DoorSystemSettingViewController

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
#pragma mark - --------------------------设置代理--------------------------
    if (_camera != nil)
        _camera.delegate2 = self;
    
    pushNotification = [self readSQListPushNotification];
    
    [self searchDeviceStuas];
    
    
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    [self setNavigationStyle];
    _camera = [AppDelegate globalDelegate].cameraModel;
    pushNotification = -1;
    videoQuality = -1;
    recordingMode = -1;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(backrootview) name:@"backrootview" object:nil];
    
    /*  SMsgAVIoctrlThirdpartReq *s4 = (SMsgAVIoctrlThirdpartReq *)malloc(sizeof(SMsgAVIoctrlThirdpartReq));
     memset(s4, 0, sizeof(SMsgAVIoctrlThirdpartReq));
     
     s4 ->value1_ = 1;
     
     [camera sendIOCtrlToChannel:0
     Type:THIRD_PART_SET_WARNING_STATUS
     Data:(char *)s4
     DataSize:sizeof(SMsgAVIoctrlThirdpartReq)];
     free(s4);
     */
}

- (void)backrootview{
    
#pragma mark - --------------------------写一个取消定时器的通知--------------------------
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [SVProgressHUD dismiss];

        [[NSNotificationCenter defaultCenter] postNotificationName:@"backVC" object:nil];
        
    });


    

}
- (void)searchDeviceStuas{
    
    // get video quality
    SMsgAVIoctrlGetStreamCtrlReq *structVideoQuality = malloc(sizeof(SMsgAVIoctrlGetStreamCtrlReq));
    memset(structVideoQuality, 0, sizeof(SMsgAVIoctrlGetStreamCtrlReq));
    
    [_camera sendIOCtrlToChannel:0
                           Type:IOTYPE_USER_IPCAM_GETSTREAMCTRL_REQ
                           Data:(char *)structVideoQuality
                       DataSize:sizeof(SMsgAVIoctrlGetStreamCtrlReq)];
    free(structVideoQuality);
    
    // get video flip
    SMsgAVIoctrlGetVideoModeReq *structVideoFlip = malloc(sizeof(SMsgAVIoctrlGetVideoModeReq));
    memset(structVideoFlip, 0, sizeof(SMsgAVIoctrlGetVideoModeReq));
    structVideoFlip->channel = 0;
    
    [_camera sendIOCtrlToChannel:0
                           Type:IOTYPE_USER_IPCAM_GET_VIDEOMODE_REQ
                           Data:(char *)structVideoFlip
                       DataSize:sizeof(SMsgAVIoctrlGetVideoModeReq)];
    free(structVideoFlip);
    
    
    // get Env Mode
    SMsgAVIoctrlGetEnvironmentReq *structEnvMode = malloc(sizeof(SMsgAVIoctrlGetEnvironmentReq));
    memset(structEnvMode, 0, sizeof(SMsgAVIoctrlGetEnvironmentReq));
    structEnvMode->channel = 0;
    
    [_camera sendIOCtrlToChannel:0
                           Type:IOTYPE_USER_IPCAM_GET_ENVIRONMENT_REQ
                           Data:(char *)structEnvMode
                       DataSize:sizeof(SMsgAVIoctrlGetEnvironmentReq)];
    free(structEnvMode);
    
    // get TimeZone info
    SMsgAVIoctrlTimeZone *structTZ = malloc(sizeof(SMsgAVIoctrlTimeZone));
    memset(structTZ, 0, sizeof(SMsgAVIoctrlTimeZone));
    
    [_camera sendIOCtrlToChannel:0
                           Type:IOTYPE_USER_IPCAM_GET_TIMEZONE_REQ
                           Data:(char *)structTZ
                       DataSize:sizeof(SMsgAVIoctrlTimeZone)];
    free(structTZ);
    
    
    
    // get MotionDetection info
    SMsgAVIoctrlGetMotionDetectReq *structMotionDetection = malloc(sizeof(SMsgAVIoctrlGetMotionDetectReq));
    memset(structMotionDetection, 0, sizeof(SMsgAVIoctrlGetMotionDetectReq));
    
    structMotionDetection->channel = 0;
    [_camera sendIOCtrlToChannel:0
                           Type:IOTYPE_USER_IPCAM_GETMOTIONDETECT_REQ
                           Data:(char *)structMotionDetection
                       DataSize:sizeof(SMsgAVIoctrlGetMotionDetectReq)];
    free(structMotionDetection);
    
    
    // get RecordingMode info
    SMsgAVIoctrlGetRecordReq *structRecordingMode = malloc(sizeof(SMsgAVIoctrlGetRecordReq));
    memset(structRecordingMode, 0, sizeof(SMsgAVIoctrlGetRecordReq));
    
    structRecordingMode->channel = 0;
    [_camera sendIOCtrlToChannel:0
                           Type:IOTYPE_USER_IPCAM_GETRECORD_REQ
                           Data:(char *)structRecordingMode
                       DataSize:sizeof(SMsgAVIoctrlGetRecordReq)];
    free(structRecordingMode);
    
    
}

#pragma mark - SQList (push_notification) Methods
- (NSInteger)readSQListPushNotification
{
    NSInteger push_notification = -1;
    
    FMResultSet *rs = [[AppDelegate globalDelegate].database executeQuery:@"SELECT * FROM notification WHERE dev_uid=?", _camera.uid];
    
    while([rs next]) {
        push_notification = [rs intForColumn:@"push_notification"];
        NSLog(@"UID(%@) push_notification:%ld", _camera.uid, (long)push_notification);
    }
    [rs close];
    
    return push_notification;
}

#pragma mark - MyCameraDelegate Methods
- (void)camera:(MyCamera *)camera_ _didReceiveIOCtrlWithType:(NSInteger)type Data:(const char *)data DataSize:(NSInteger)size {
    
    if (camera_ == _camera) {
        
        if (type == IOTYPE_USER_IPCAM_GETSTREAMCTRL_RESP) {
            
            SMsgAVIoctrlGetStreamCtrlResq *s = (SMsgAVIoctrlGetStreamCtrlResq*)data;
            videoQuality = [self qualityDeviceToView:s->quality];
            
            //            [self.tableView reloadData];
        }
        else if (type == IOTYPE_USER_IPCAM_GET_VIDEOMODE_RESP) {
            
            SMsgAVIoctrlGetVideoModeResp *s = (SMsgAVIoctrlGetVideoModeResp*)data;
            //            videoFlip = s->mode;
            
            //            [self.tableView reloadData];
        }
        else if (type == IOTYPE_USER_IPCAM_GET_ENVIRONMENT_RESP) {
            
            SMsgAVIoctrlGetEnvironmentResp *s = (SMsgAVIoctrlGetEnvironmentResp*)data;
            //            envMode = s->mode;
            
            //            [self.tableView reloadData];
        }
        else if (type == IOTYPE_USER_IPCAM_LISTWIFIAP_RESP) {
            
            SMsgAVIoctrlListWifiApResp *s = (SMsgAVIoctrlListWifiApResp *)data;
            //            wifiStatus = 0;
            
            for (int i = 0; i < s->number; ++i) {
                
                SWifiAp ap = s->stWifiAp[i];
                
                //                if (ap.status == 1 || ap.status == 2 || ap.status == 3 || ap.status == 4) {
                //                    self.wifiSSID = [[NSString alloc] initWithCString:ap.ssid encoding:NSUTF8StringEncoding];
                //                    wifiStatus = ap.status;
                //                }
                
            }
            
            //            isRecvWiFi = true;
            
            //            [self.tableView reloadData];
        }
        else if (type == IOTYPE_USER_IPCAM_GETMOTIONDETECT_RESP) {
            
            SMsgAVIoctrlGetMotionDetectResp *s = (SMsgAVIoctrlGetMotionDetectResp*)data;
            //            motionDetection = s->sensitivity;
            //
            //            [self.tableView reloadData];
        }
        else if (type == IOTYPE_USER_IPCAM_GETRECORD_RESP) {
            
            SMsgAVIoctrlGetRecordResq *s = (SMsgAVIoctrlGetRecordResq*)data;
            recordingMode = s->recordType;
            //
            //            [self.tableView reloadData];
        }
        else if (type == IOTYPE_USER_IPCAM_GETWIFI_RESP) {
            
            //            wifiStatus = 0;
            SMsgAVIoctrlGetWifiResp *s = (SMsgAVIoctrlGetWifiResp *)data;
            
            //            self.wifiSSID = [[NSString alloc] initWithCString:(const char*)s->ssid encoding:NSUTF8StringEncoding];
            //            wifiStatus = s->status;
            //
            //            isRecvWiFi = true;
            //            [self.tableView reloadData];
        }
        else if (type == IOTYPE_USER_IPCAM_GETWIFI_RESP_2) {
            
            //            wifiStatus = 0;
            SMsgAVIoctrlGetWifiResp2 *s = (SMsgAVIoctrlGetWifiResp2 *)data;
            
            //            self.wifiSSID = [[NSString alloc] initWithCString:(const char*)s->ssid encoding:NSUTF8StringEncoding];
            //            wifiStatus = s->status;
            //
            //            isRecvWiFi = true;
            //            [self.tableView reloadData];
        }
        else if (type == IOTYPE_USER_IPCAM_GET_TIMEZONE_RESP) {
            
            SMsgAVIoctrlTimeZone *s = (SMsgAVIoctrlTimeZone*)data;
            
            NSLog(@"EG: IOTYPE_USER_IPCAM_GET_TIMEZONE_RESP s->cbSize:%d, s->nIsSupportTimeZone:%d, s->nGMTDiff:%d, s->szTimeZoneString:%s",
                  s->cbSize, s->nIsSupportTimeZone, s->nGMTDiff, s->szTimeZoneString);
            
            //            isSupportTZ = (0 == s->nIsSupportTimeZone) ? false : true;
            //            timeZone = s->nGMTDiff;
            //
            //            [self.tableView reloadData];
            
        }
        
              
    }
}

#pragma mark - Conversion Quality Methods

- (NSInteger)qualityDeviceToView:(NSInteger) _quality{
    NSInteger r_quality;
    
    switch (_quality) {
        case AVIOCTRL_QUALITY_UNKNOWN:
            r_quality = VIEW_VIDEO_QAULITY_PRIORITY;
            break;
        case AVIOCTRL_QUALITY_MAX:
            r_quality = VIEW_HD_VIDEO_QAULITY;
            break;
        case AVIOCTRL_QUALITY_HIGH:
            r_quality = VIEW_HD_VIDEO_QAULITY;
            break;
        case AVIOCTRL_QUALITY_MIDDLE:
            r_quality = VIEW_VIDEO_QAULITY_PRIORITY;
            break;
        case AVIOCTRL_QUALITY_LOW:
            r_quality = VIEW_VIDEO_QAULITY_PRIORITY;
            break;
        case AVIOCTRL_QUALITY_MIN:
            r_quality = VIEW_SMOOTH_VIDEO_PRIORITY;
            break;
        default:
            r_quality = VIEW_VIDEO_QAULITY_PRIORITY;
            break;
    }
    
    return r_quality;
}

- (NSInteger)qualityViewToDevice:(NSInteger) _quality{
    NSInteger r_quality;
    
    switch (_quality) {
        case VIEW_HD_VIDEO_QAULITY:
            r_quality = AVIOCTRL_QUALITY_MAX;
            break;
        case VIEW_VIDEO_QAULITY_PRIORITY:
            r_quality = AVIOCTRL_QUALITY_MIDDLE;
            break;
        case VIEW_SMOOTH_VIDEO_PRIORITY:
            r_quality = AVIOCTRL_QUALITY_MIN;
            break;
        default:
            r_quality = AVIOCTRL_QUALITY_MIDDLE;
            break;
    }
    
    return r_quality;
}

#pragma mark - --------------------------UITableView dataSource--------------------------

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return self.settingPlist.count;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return [self.settingPlist[section] count];
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        cell.textLabel.textColor = [UIColor colorWithHexString:@"#56504f"];
        [cell.textLabel setFont:[UIFont systemFontOfSize:15.f]];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    }
    
    NSDictionary *config = self.settingPlist[indexPath.section][indexPath.row];
    cell.imageView.image = [UIImage imageNamed:config[@"img"]];
    cell.textLabel.text = config[@"title"];
    
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 49.f;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 10;
    
}
#pragma mark - --------------------------UITableView delegate--------------------------

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    switch (indexPath.section) {
        case 0:
        {
            switch (indexPath.row) {
                case 0:
                {
                    DoorSystemDeviceInfoViewController *deviceInfoVC = [[DoorSystemDeviceInfoViewController alloc]init];
                    self.hidesBottomBarWhenPushed = YES;
                    [self.navigationController pushViewController:deviceInfoVC animated:YES];
                    self.hidesBottomBarWhenPushed = NO;
                    break;
                }
                    
                default:
                    break;
            }
            break;
        }
        case 1:
        {
            switch (indexPath.row) {
                case 0:
                {
                    
                    if (_camera != nil && _camera.sessionState == CONNECTION_STATE_CONNECTED && [_camera getConnectionStateOfChannel:0] == CONNECTION_STATE_CONNECTED) {
                        DoorSystemWiFiViewController *vc = [DoorSystemWiFiViewController new];
                        self.hidesBottomBarWhenPushed = YES;
                        [self.navigationController pushViewController:vc animated:YES];
                        self.hidesBottomBarWhenPushed = NO;
                    
                    }else{
                        
                        [SVProgressHUD showInfoWithStatus:@"设备正在连接当中..."];
                    }
                    
                    break;
                }
                case 1:
                {
                    if (_camera != nil && _camera.sessionState == CONNECTION_STATE_CONNECTED && [_camera getConnectionStateOfChannel:0] == CONNECTION_STATE_CONNECTED) {
                        DoorSystemPwdSettingViewController *dsPwdSettingVC = [[DoorSystemPwdSettingViewController alloc]init];
                        self.hidesBottomBarWhenPushed = YES;
                        [self.navigationController pushViewController:dsPwdSettingVC animated:YES];
                        self.hidesBottomBarWhenPushed = NO;

                    }else{
                        
                        [SVProgressHUD showInfoWithStatus:@"设备正在连接当中..."];
                    }
                    break;
                }
                case 2:
                {
                    if (_camera != nil && _camera.sessionState == CONNECTION_STATE_CONNECTED && [_camera getConnectionStateOfChannel:0] == CONNECTION_STATE_CONNECTED) {
                    DoorSystemPushSettingViewController *pushSettingVC = [[DoorSystemPushSettingViewController alloc]init];
                    self.hidesBottomBarWhenPushed = YES;
                    [self.navigationController pushViewController:pushSettingVC animated:YES];
                    self.hidesBottomBarWhenPushed = NO;
                    }else{
                        
                        [SVProgressHUD showInfoWithStatus:@"设备正在连接当中..."];
                    }
                    break;
                }
                case 3:
                {
                    if (_camera != nil && _camera.sessionState == CONNECTION_STATE_CONNECTED && [_camera getConnectionStateOfChannel:0] == CONNECTION_STATE_CONNECTED) {
                    
                        DoorSystemVideoSettingViewController *videoSettingVC = [[DoorSystemVideoSettingViewController alloc]init];
                        
                        switch (recordingMode) {
                            case 0:
                            {
                                videoSettingVC.indexpathTag = 666;
                                
                            }
                                break;
                                
                            case 1:
                            {
                                videoSettingVC.indexpathTag = 0;
                            }
                                break;
                            case 2:
                            {
                                videoSettingVC.indexpathTag = 1;
                            }
                                break;
                                
                            default:
                                break;
                        }
                        self.hidesBottomBarWhenPushed = YES;
                        [self.navigationController pushViewController:videoSettingVC animated:YES];
                        self.hidesBottomBarWhenPushed = NO;

                    }else{
                        
                        [SVProgressHUD showInfoWithStatus:@"设备正在连接当中..."];
                    }
                    
                    break;
                }
                case 4:
                {
 

                  
                    if (_camera != nil && _camera.sessionState == CONNECTION_STATE_CONNECTED && [_camera getConnectionStateOfChannel:0] == CONNECTION_STATE_CONNECTED) {
                        
                        DoorSystemAlarmAccessViewController *vc = [[DoorSystemAlarmAccessViewController alloc] init];
                        self.hidesBottomBarWhenPushed = YES;
                        vc.camera = [AppDelegate globalDelegate].cameraModel;
                        [self.navigationController pushViewController:vc animated:YES];
                        self.hidesBottomBarWhenPushed = NO;

                    }else{
                        
                        [SVProgressHUD showInfoWithStatus:@"设备正在连接当中..."];

                    }
               
                   

                }
                    break;
                case 5:
                {
                    if (_camera != nil && _camera.sessionState == CONNECTION_STATE_CONNECTED && [_camera getConnectionStateOfChannel:0] == CONNECTION_STATE_CONNECTED) {
                        DoorSystemSDCardViewController *vc = [DoorSystemSDCardViewController new];
                        self.hidesBottomBarWhenPushed = YES;
                        [self.navigationController pushViewController:vc animated:YES];
                        self.hidesBottomBarWhenPushed = NO;
                    }else{
                        
                        [SVProgressHUD showInfoWithStatus:@"设备正在连接当中..."];
                    }
                   
                }
                    break;
                default:
                    break;
            }
            break;
        }
        case 2:
        {
            switch (indexPath.row) {
                case 0:
                {
                    
                    if (_camera != nil && _camera.sessionState == CONNECTION_STATE_CONNECTED && [_camera getConnectionStateOfChannel:0] == CONNECTION_STATE_CONNECTED) {
                        DoorSystemUPdateViewController *vc = [DoorSystemUPdateViewController new];
                        self.hidesBottomBarWhenPushed = YES;
                        [self.navigationController pushViewController:vc animated:YES];
                        self.hidesBottomBarWhenPushed = NO;

                    
                    }else{
                        
                        [SVProgressHUD showInfoWithStatus:@"设备正在连接当中..."];
                    }
                    break;
                }
                case 1:
                {
                    __weak typeof(self) weakself = self;
                    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"警告" message:@"是否确定删除该设备？" preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault
                                                                     handler:^(UIAlertAction * action) {
                                                                         
                                                                         NSLog(@"删除设备");
                                                                         
                                                                         MAIN(^{
                                                                             
                                                                             [SVProgressHUD showWithStatus:@"清理设备信息中..."];
                                                                             
                                                                             for (int i=0; i<10; i++) {
                                                                                 
                                                                                 if (0 == [[AppDelegate globalDelegate].camera_list count]) {
                                                                                     NSLog(@"[searchedData count] == 0  i=%d", i);
                                                                                 }
                                                                                 
                                                                                 // usleep(300*1000);
                                                                             }
                                                                             if (0 == [[AppDelegate globalDelegate].camera_list count]) {
                                                                                 NSLog(@"[searchedData count] == 0  return");
                                                                                 return;
                                                                             }
                                                                             
                                                                             
                                                                             NSString *uid = nil;
                                                                             
                                                                             //NSLog(@"tableView commitEditingStyle forRowAtIndexPath, searchedData.count=%d, row=%d", searchedData.count, [indexPath row]);
                                                                             
                                                                             [weakself.camera stop:0];
                                                                             if (weakself.camera.sessionState == CONNECTION_STATE_CONNECTED) {
                                                                                 [weakself.camera disconnect];
                                                                             }
                                                                             else
                                                                             {
                                                                             }
                                                                             
                                                                             uid = weakself.camera.uid;
                                                                             
                                                                             [[AppDelegate globalDelegate].camera_list removeObject:weakself.camera];
                                                                             
                                                                             if (uid != nil) {
                                                                                 
                                                                                 // delete camera & snapshot file in db
                                                                                 [self deleteCamera:uid];
                                                                                 [self deleteSnapshotRecords:uid];
                                                                                 
                                                                                 // delete record  & event in db
                                                                                 [self deleteVideoRecords:uid];
                                                                                 [self deleteEvents:uid];
                                                                                 
                                                                                 
                                                                                 // set notification file -> delete
                                                                                 if ([AppDelegate globalDelegate].database != NULL) {
                                                                                     if (![[AppDelegate globalDelegate].database executeUpdate:@"UPDATE notification SET push_notification=? WHERE dev_uid=?", [NSNumber numberWithInt:0], uid]) {
                                                                                         NSLog(@"Fail to update device to database.");
                                                                                     }
                                                                                 }
                                                                                 
                                                                                 // unregister from apns server
                                                                                 dispatch_queue_t queue = dispatch_queue_create("apns-reg_client", NULL);
                                                                                 dispatch_async(queue, ^{
                                                                                     
                                                                                 });
                                                                                 
                                                                             }
                                                                             
                                                                             [self backrootview];

                                                                             
                                                                         });
                                                                         
                                                                         
                                                                         
                                                                     }];
                    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel
                                                                         handler:^(UIAlertAction * action) {}];
                    [alertVC addAction:okAction];
                    [alertVC addAction:cancelAction];
                    [self presentViewController:alertVC animated:YES completion:nil];
                    break;
                }
                    
                default:
                    break;
            }
            break;
        }
        default:
            break;
    }
    
}


- (void)deleteCamera:(NSString *)uid {
    
    /* delete camera lastframe snapshot file */
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *imgName = [NSString stringWithFormat:@"%@.jpg", uid];
    [fileManager removeItemAtPath:[self pathForDocumentsResource: imgName] error:NULL];
    
    if ([AppDelegate globalDelegate].database != NULL) {
        
        if (![[AppDelegate globalDelegate].database executeUpdate:@"DELETE FROM device where dev_uid=?", uid]) {
            NSLog(@"Fail to remove device from database.");
        }
    }
}

- (NSString *) pathForDocumentsResource:(NSString *) relativePath {
    
    static NSString* documentsPath = nil;
    
    if (nil == documentsPath) {
        
        NSArray* dirs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        documentsPath = [dirs objectAtIndex:0];
    }
    
    return [documentsPath stringByAppendingPathComponent:relativePath];
}
- (void)deleteSnapshotRecords:(NSString *)uid {
    
    if ([AppDelegate globalDelegate].database != NULL) {
        
        FMResultSet *rs = [[AppDelegate globalDelegate].database executeQuery:@"SELECT * FROM snapshot WHERE dev_uid=?", uid];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        while([rs next]) {
            
            NSString *filePath = [rs stringForColumn:@"file_path"];
            [fileManager removeItemAtPath:[self pathForDocumentsResource: filePath] error:NULL];
            NSLog(@"camera(%@) snapshot removed", filePath);
        }
        
        [rs close];
        
        [[AppDelegate globalDelegate].database executeUpdate:@"DELETE FROM snapshot WHERE dev_uid=?", uid];
    }
}

- (void)deleteVideoRecords:(NSString *)uid {
    
    if ([AppDelegate globalDelegate].database != NULL) {
        
        FMResultSet *rs = [[AppDelegate globalDelegate].database executeQuery:@"SELECT * FROM record WHERE dev_uid=?", uid];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        while([rs next]) {
            
            NSString *filePath = [rs stringForColumn:@"file_path"];
            [fileManager removeItemAtPath:[self pathForDocumentsResource: [NSString stringWithFormat:@"%@.mp4", filePath]] error:NULL];
            NSLog(@"camera(%@) record removed", [NSString stringWithFormat:@"%@.mp4", filePath]);
            [fileManager removeItemAtPath:[self pathForDocumentsResource: [NSString stringWithFormat:@"%@.t.jpg", filePath]] error:NULL];
            NSLog(@"camera(%@) record removed", [NSString stringWithFormat:@"%@.t.jpg", filePath]);
        }
        
        [rs close];
        
        [[AppDelegate globalDelegate].database executeUpdate:@"DELETE FROM record WHERE dev_uid=?", uid];
    }
}

- (void)deleteEvents:(NSString *)uid {
    
    if ([AppDelegate globalDelegate].database != NULL) {
        
        [[AppDelegate globalDelegate].database executeUpdate:@"DELETE FROM event WHERE dev_uid=?", uid];
    }
}

- (void)deleteNotifications:(NSString *)uid {
    
    if ([AppDelegate globalDelegate].database != NULL) {
        
        [[AppDelegate globalDelegate].database executeUpdate:@"DELETE FROM notification WHERE dev_uid=?", uid];
    }
}


- (UITableView *)tableView{
    
    if (!_tableView) {
        
        __weak UIView *superView = self.view;
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        [superView addSubview:_tableView];
        //        _tableView.separatorStyle = UITableViewCellSelectionStyleNone;//隐藏tableView的分割线
        //        _tableView.scrollEnabled = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
    }
    
    return _tableView;
    
}

- (NSArray *)settingPlist{
    
    if (!_settingPlist) {
        
        _settingPlist = [[NSArray alloc]initWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"DoorSystemSetting" ofType:@"plist"]];
        
    }
    
    return _settingPlist;
    
}

- (void)setNavigationStyle{
    
    [self setNavigationTitle:@"设置" titleColor:[UIColor colorWithRed:210/255.0 green:177/255.0 blue:104/255.0 alpha:1]];
    
}

- (void)masLayoutSubview{
    
    __weak UIView *superView = self.view;
    [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(superView.mas_top);
        make.left.mas_equalTo(superView.mas_left);
        make.right.mas_equalTo(superView.mas_right);
        make.bottom.mas_equalTo(superView.mas_bottom).mas_offset(-44);
        
    }];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}



@end
